/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package vista;

import java.awt.event.KeyEvent;
import java.util.ArrayList;
import javax.swing.DefaultListModel;
import javax.swing.JOptionPane;
import modelo.Intervalo;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.ChartFrame;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.plot.PlotOrientation;
import org.jfree.data.category.DefaultCategoryDataset;


/**
 *
 * @author juan
 */
public class FrecuenciaRandomLenguaje extends javax.swing.JFrame {
     
    
    private DefaultCategoryDataset dataset;
    private int cant_Numeros;
    private int cant_Intervalos;
    private DefaultListModel listModel;
    double arreglo[];
    private ArrayList<Double> numeros;
    Intervalo intervalo[];
    double amplitud;
    double frecuencia_Esperada;
      
    
    /**
     * Creates new form FrecuenciaRandomLenguaje
     */
    public FrecuenciaRandomLenguaje() {
        initComponents();
        this.setLocationRelativeTo(null);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        pnl_Datos = new javax.swing.JPanel();
        lbl_Cant_Numeros = new javax.swing.JLabel();
        lbl_Cant_Intervalos = new javax.swing.JLabel();
        txt_Cant_Numeros = new javax.swing.JTextField();
        txt_Cant_Intervalos = new javax.swing.JTextField();
        btn_Graficar = new javax.swing.JButton();
        btn_Generar = new javax.swing.JButton();
        pnl_Numeros = new javax.swing.JPanel();
        scroll_Lista = new javax.swing.JScrollPane();
        lst_Numeros = new javax.swing.JList();
        btn_Cerrar = new javax.swing.JButton();
        btn_Limpiar = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setTitle("Generador de Números Aleatorios - Random del Lengüaje");

        pnl_Datos.setBorder(javax.swing.BorderFactory.createTitledBorder("Datos"));

        lbl_Cant_Numeros.setText("Cantidad de numeros a generar: ");

        lbl_Cant_Intervalos.setText("Cantidad de intervalos: ");

        txt_Cant_Numeros.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_Cant_NumerosKeyPressed(evt);
            }
        });

        txt_Cant_Intervalos.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                txt_Cant_IntervalosKeyPressed(evt);
            }
        });

        javax.swing.GroupLayout pnl_DatosLayout = new javax.swing.GroupLayout(pnl_Datos);
        pnl_Datos.setLayout(pnl_DatosLayout);
        pnl_DatosLayout.setHorizontalGroup(
            pnl_DatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl_DatosLayout.createSequentialGroup()
                .addContainerGap()
                .addGroup(pnl_DatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(lbl_Cant_Numeros)
                    .addComponent(lbl_Cant_Intervalos))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(pnl_DatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(txt_Cant_Numeros, javax.swing.GroupLayout.DEFAULT_SIZE, 49, Short.MAX_VALUE)
                    .addComponent(txt_Cant_Intervalos))
                .addContainerGap())
        );
        pnl_DatosLayout.setVerticalGroup(
            pnl_DatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl_DatosLayout.createSequentialGroup()
                .addGroup(pnl_DatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txt_Cant_Numeros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_Cant_Numeros))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(pnl_DatosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(txt_Cant_Intervalos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(lbl_Cant_Intervalos))
                .addGap(0, 15, Short.MAX_VALUE))
        );

        btn_Graficar.setText("Graficar");
        btn_Graficar.setEnabled(false);
        btn_Graficar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_GraficarActionPerformed(evt);
            }
        });

        btn_Generar.setText("Generar");
        btn_Generar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_GenerarActionPerformed(evt);
            }
        });

        pnl_Numeros.setBorder(javax.swing.BorderFactory.createTitledBorder("Lista de Números"));

        scroll_Lista.setViewportView(lst_Numeros);

        javax.swing.GroupLayout pnl_NumerosLayout = new javax.swing.GroupLayout(pnl_Numeros);
        pnl_Numeros.setLayout(pnl_NumerosLayout);
        pnl_NumerosLayout.setHorizontalGroup(
            pnl_NumerosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl_NumerosLayout.createSequentialGroup()
                .addContainerGap()
                .addComponent(scroll_Lista, javax.swing.GroupLayout.DEFAULT_SIZE, 190, Short.MAX_VALUE)
                .addContainerGap())
        );
        pnl_NumerosLayout.setVerticalGroup(
            pnl_NumerosLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(pnl_NumerosLayout.createSequentialGroup()
                .addComponent(scroll_Lista, javax.swing.GroupLayout.DEFAULT_SIZE, 302, Short.MAX_VALUE)
                .addContainerGap())
        );

        btn_Cerrar.setText("Cerrar");
        btn_Cerrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_CerrarActionPerformed(evt);
            }
        });

        btn_Limpiar.setText("Limpiar");
        btn_Limpiar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btn_LimpiarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(pnl_Datos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                                .addComponent(btn_Limpiar)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_Graficar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btn_Generar, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE)))
                        .addGap(18, 18, 18)
                        .addComponent(pnl_Numeros, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGap(0, 0, Short.MAX_VALUE)
                        .addComponent(btn_Cerrar)))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.HORIZONTAL, new java.awt.Component[] {btn_Generar, btn_Graficar, btn_Limpiar});

        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(pnl_Datos, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                .addComponent(btn_Graficar)
                                .addComponent(btn_Limpiar))
                            .addComponent(btn_Generar)))
                    .addComponent(pnl_Numeros, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(btn_Cerrar)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void btn_GraficarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_GraficarActionPerformed
        
        dataset = new DefaultCategoryDataset();
        
        for (int i=0; i < intervalo.length; i++){
            
            dataset.addValue(intervalo[i].getContador(), "Frecuencia Observada" ,"[" + intervalo[i].getLimInferior() + " - " + intervalo[i].getLimSuperior()+"]");
        }
        
        for (int i=0; i < intervalo.length; i++){
            
            dataset.addValue(this.frecuencia_Esperada, "Frecuencia Esperada","[" + intervalo[i].getLimInferior() + " - " + intervalo[i].getLimSuperior()+"]");
        }            
        
        JFreeChart chart= ChartFactory.createBarChart3D("Distribucion de Frecuencias", "Intervalos", "Frecuencia", dataset, PlotOrientation.VERTICAL,false,true,false);
        
        ChartFrame frame = new ChartFrame("Grafico de barras", chart);
        //frame.setLocationRelativeTo(null);
        frame.pack();
        frame.setExtendedState(ChartFrame.MAXIMIZED_BOTH);
        frame.setVisible(true);    
    }//GEN-LAST:event_btn_GraficarActionPerformed

    private void btn_GenerarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_GenerarActionPerformed
        
        this.listModel.removeAllElements();
        
        if (this.txt_Cant_Numeros.getText().equals("") || this.txt_Cant_Intervalos.getText().equals("")){
            JOptionPane.showMessageDialog(FrecuenciaRandomLenguaje.super.getContentPane(),"Faltan los datos de la cantidad de intervalos o la cantidad de numeros", "Importante", JOptionPane.INFORMATION_MESSAGE);
        }
        else{
            
            listModel = new DefaultListModel();
            this.lst_Numeros.setModel(listModel);
            
            cant_Numeros = Integer.parseInt(this.txt_Cant_Numeros.getText());
            cant_Intervalos = Integer.parseInt(this.txt_Cant_Intervalos.getText());
            
            arreglo= new double[cant_Numeros];
            intervalo = new Intervalo[cant_Intervalos];
            amplitud= (double) 1/cant_Intervalos;
            numeros = new ArrayList<Double>(cant_Numeros);
            System.out.println(amplitud);
            double lim_Inferior=0;
            double lim_Superior=amplitud;
            int i;
            frecuencia_Esperada= this.cant_Numeros/this.cant_Intervalos;
            
            for (i=0; i<cant_Intervalos; i++)
            {
                intervalo[i]= new Intervalo(lim_Inferior,lim_Superior);
                lim_Inferior= lim_Superior;
                lim_Superior= lim_Superior+amplitud;
            }
                
            for (i=0; i < cant_Numeros ; i ++)
            {
                double numero = (Math.random());
                listModel.addElement(numero);
                arreglo[i]= numero;
                numeros.add(numero);
            }
            
            for (int j=0; j < cant_Intervalos; j++){
                
                for (i=0; i < cant_Numeros ; i ++){
                    
                    if(numeros.get(i) >=intervalo[j].getLimInferior() && numeros.get(i) <intervalo[j].getLimSuperior()){
                        intervalo[j].agregarNumero(lim_Superior);
                    }
                }
            }
            this.btn_Graficar.setEnabled(true);
        }
    }//GEN-LAST:event_btn_GenerarActionPerformed

    private void btn_CerrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_CerrarActionPerformed
        Principal miPrincipal= new Principal();
        miPrincipal.setVisible(true);
        this.setVisible(false);
        
    }//GEN-LAST:event_btn_CerrarActionPerformed

    private void txt_Cant_NumerosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_Cant_NumerosKeyPressed
        char caracter = evt.getKeyChar();
        
        if (!((Character.isDigit(caracter) || (caracter == KeyEvent.VK_BACK_SPACE))))
        {
            JOptionPane.showMessageDialog(FrecuenciaRandomLenguaje.super.getContentPane(), "Ingrese solo numeros!", "Importante", JOptionPane.INFORMATION_MESSAGE);
            this.txt_Cant_Numeros.setText("");
        }
    }//GEN-LAST:event_txt_Cant_NumerosKeyPressed

    private void txt_Cant_IntervalosKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_txt_Cant_IntervalosKeyPressed
            char caracter = evt.getKeyChar();
        
        if (!((Character.isDigit(caracter) || (caracter == KeyEvent.VK_BACK_SPACE))))
        {
            JOptionPane.showMessageDialog(FrecuenciaRandomLenguaje.super.getContentPane(), "Ingrese solo numeros!", "Importante", JOptionPane.INFORMATION_MESSAGE);
            this.txt_Cant_Intervalos.setText("");
        }
    }//GEN-LAST:event_txt_Cant_IntervalosKeyPressed

    private void btn_LimpiarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btn_LimpiarActionPerformed
       this.txt_Cant_Intervalos.setText("");
       this.txt_Cant_Numeros.setText("");
       this.listModel.clear();
       this.btn_Graficar.setEnabled(false);
    }//GEN-LAST:event_btn_LimpiarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(FrecuenciaRandomLenguaje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(FrecuenciaRandomLenguaje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(FrecuenciaRandomLenguaje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(FrecuenciaRandomLenguaje.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {

            @Override
            public void run() {
                new FrecuenciaRandomLenguaje().setVisible(true);

            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton btn_Cerrar;
    private javax.swing.JButton btn_Generar;
    private javax.swing.JButton btn_Graficar;
    private javax.swing.JButton btn_Limpiar;
    private javax.swing.JLabel lbl_Cant_Intervalos;
    private javax.swing.JLabel lbl_Cant_Numeros;
    private javax.swing.JList lst_Numeros;
    private javax.swing.JPanel pnl_Datos;
    private javax.swing.JPanel pnl_Numeros;
    private javax.swing.JScrollPane scroll_Lista;
    private javax.swing.JTextField txt_Cant_Intervalos;
    private javax.swing.JTextField txt_Cant_Numeros;
    // End of variables declaration//GEN-END:variables
}
